import socket from '../../utils/socket';
export default {
    name: 'remote1',
    data() {
        return {
            account: window.sessionStorage.account || '',
            isJoin: false,
            userList: [],
            roomid: 'webrtc_1v1', // 指定房间ID
            isCall: false, // 正在通话的对象
            loading: false,
            loadingText: '呼叫中',
            isToPeer: false, // 是否建立了 P2P 连接
            peer: null,
            offerOption: {
                offerToReceiveAudio: 1,
                offerToReceiveVideo: 1
            },
            //下面是我新加的
            longstream: null,
            user: {},
            search: '',
            text: '',
            target: null, //聊天目标
            pageChat: {}, //聊天框
        };
    },
    methods: {
        // 登录相关开始
        /*
           房间ID roomid 为 活动 activityId 
           登录名 account 为 userId
           window.sessionStorage 用于临时保存同一窗口(或标签页)的数据，刷新还在保存 在关闭窗口或标签页之后将会删除这些数据。
        */
        join() {
            if (!this.account) return;
            this.isJoin = true;
            window.sessionStorage.account = this.account;
            socket.emit('join', { roomid: this.roomid, account: this.account });
        },
        // 登录相关结束

        // 文字聊天开始
        // 接收
        acceptText(data) {
            if (!Object.keys(this.pageChat).includes(data.self)) {
                this.pageChat[data.self] = []
            }
            this.pageChat[data.self].push(data)
        },
        // 发送
        sendText() {
            if (!this.text || !this.target) return
            let data = { account: this.target.account, self: this.account, type: '4', text: this.text, data: new Date().toLocaleString() }
            socket.emit('reply', data)
            if (!Object.keys(this.pageChat).includes(this.target.account)) {
                this.pageChat[this.target.account] = []
            }
            this.pageChat[this.target.account].push(data)
            this.text = ''
        },
        // 文字聊天结束

        // 纯语音聊天开始
        // 纯语音聊天结束

        // 视频语音聊天开始
        myapply() {
            if (!this.target) return
            this.apply(this.target.account)
        },
        // 视频语音聊天结束

        // socket 连接相关 开始
        // socket 连接相关 结束

        // RTCPeerConnection 相关开始
        // RTCPeerConnection 相关结束

        // video 流相关 开始
        // video 流相关 结束

        initSocket() {
            socket.on('joined', (data) => { // 收到登录
                this.userList = data;
                console.log(data)
            });
            socket.on('reply', async data => { // 收到回复
                this.loading = false;
                console.log(data);
                switch (data.type) {
                    case '1': // 同意
                        this.isCall = data.self;
                        // 对方同意之后创建自己的 peer
                        await this.createP2P(data);
                        // 并给对方发送 offer
                        this.createOffer(data);
                        break;
                    case '2': //拒绝
                        this.$message({
                            message: '对方拒绝了你的请求！',
                            type: 'warning'
                        });
                        break;
                    case '3': // 正在通话中
                        this.$message({
                            message: '对方正在通话中！',
                            type: 'warning'
                        });
                        break;
                    case '4': // 发送文字
                        this.acceptText(data)
                        break;
                    default:
                        console.error('收到没有匹配的回复！')
                }
            });
            socket.on('apply', data => { // 收到请求
                if (this.isCall) {
                    this.reply(data.self, '3');
                    return;
                }
                this.$confirm(data.self + ' 向你请求视频通话, 是否同意?', '提示', {
                    confirmButtonText: '同意',
                    cancelButtonText: '拒绝',
                    type: 'warning'
                }).then(async () => {
                    await this.createP2P(data); // 同意之后创建自己的 peer 等待对方的 offer
                    this.isCall = data.self;
                    this.reply(data.self, '1');
                }).catch(() => {
                    this.reply(data.self, '2');
                });
            });
            socket.on('1v1answer', (data) => { // 接收到 answer
                this.onAnswer(data);
            });
            socket.on('1v1ICE', (data) => { // 接收到 ICE
                this.onIce(data);
            });
            socket.on('1v1offer', (data) => { // 接收到 offer
                this.onOffer(data);
            });
            socket.on('1v1hangup', _ => { // 通话挂断
                this.$message({
                    message: '对方已断开连接！',
                    type: 'warning'
                });
                this.peer.close();
                this.peer = null;
                this.isToPeer = false;
                this.isCall = false;
                this.localstream.getTracks().forEach(track => {
                    track.stop();
                });
            });
        },
        hangup() { // 挂断通话
            socket.emit('1v1hangup', { account: this.isCall, self: this.account });
            this.peer.close();
            this.peer = null;
            this.isToPeer = false;
            this.isCall = false;
            this.localstream.getTracks().forEach(track => {
                track.stop();
            });
        },
        apply(account) {
            // account 对方account  self 是自己的account
            this.loading = true;
            this.loadingText = '呼叫中';
            socket.emit('apply', { account: account, self: this.account });
        },
        reply(account, type) {
            socket.emit('reply', { account: account, self: this.account, type: type });
        },
        async createP2P(data) {
            this.loading = true;
            this.loadingText = '正在建立通话连接';
            await this.createMedia(data);
        },
        async createMedia(data) {
            // 保存本地流到全局
            try {
                // this.localstream = await navigator.mediaDevices.getUserMedia({ audio: true, video: true });
                this.localstream = await navigator.mediaDevices.getUserMedia({
                    audio: true,
                    video: {
                        aspectRatio: {
                            ideal: 1.777777 // 16:9比例优先
                        }
                    }
                });
                let video = document.querySelector('#rtcA');
                video.srcObject = this.localstream;
            } catch (e) {
                console.log('getUserMedia: ', e)
            }
            this.initPeer(data); // 获取到媒体流后，调用函数初始化 RTCPeerConnection
        },
        initPeer(data) {
            // 创建输出端 PeerConnection
            let PeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
            this.peer = new PeerConnection();
            this.peer.addStream(this.localstream); // 添加本地流
            // 监听ICE候选信息 如果收集到，就发送给对方
            this.peer.onicecandidate = (event) => {
                if (event.candidate) {
                    socket.emit('1v1ICE', { account: data.self, self: this.account, sdp: event.candidate });
                }
            };
            this.peer.onaddstream = (event) => { // 监听是否有媒体流接入，如果有就赋值给 rtcB 的 src
                this.isToPeer = true;
                this.loading = false;
                let video = document.querySelector('#rtcB');
                this.longstream = event.stream;
                video.srcObject = event.stream;
            };
        },
        async createOffer(data) { // 创建并发送 offer
            try {
                // 创建offer
                let offer = await this.peer.createOffer(this.offerOption);
                // 呼叫端设置本地 offer 描述
                await this.peer.setLocalDescription(offer);
                // 给对方发送 offer
                socket.emit('1v1offer', { account: data.self, self: this.account, sdp: offer });
            } catch (e) {
                console.log('createOffer: ', e);
            }
        },
        async onOffer(data) { // 接收offer并发送 answer
            try {
                // 接收端设置远程 offer 描述
                await this.peer.setRemoteDescription(data.sdp);
                // 接收端创建 answer
                let answer = await this.peer.createAnswer();
                // 接收端设置本地 answer 描述
                await this.peer.setLocalDescription(answer);
                // 给对方发送 answer
                socket.emit('1v1answer', { account: data.self, self: this.account, sdp: answer });
            } catch (e) {
                console.log('onOffer: ', e);
            }
        },
        async onAnswer(data) { // 接收answer
            try {
                await this.peer.setRemoteDescription(data.sdp); // 呼叫端设置远程 answer 描述
            } catch (e) {
                console.log('onAnswer: ', e);
            }
        },
        async onIce(data) { // 接收 ICE 候选
            try {
                await this.peer.addIceCandidate(data.sdp); // 设置远程 ICE
            } catch (e) {
                console.log('onAnswer: ', e);
            }
        }
    },
    mounted() {
        this.initSocket();
        if (this.account) {
            this.join();
            console.log('登录....')
        }
    }
}